package org.example.novel.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.util.Units;
import org.example.novel.domain.requ.LoginUser;
import org.example.novel.exception.CaptChaException;
import org.example.novel.service.AuthService;
import org.example.novel.utlis.JwtUtils;
import org.example.novel.utlis.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.stereotype.Service;

import static org.example.novel.constant.AuthConstant.*;

@Service
@Slf4j
public class AuthServiceImpl implements AuthService {

    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    RedisUtils redisUtils;

    @Override
    public void verifyCaptcha(String key, String code) {

        String str = redisUtils.getStr(CAPTCHA_PREFIX + key, String.class);

        if (str != null && str.equals(code)) {
            return;
        }

        throw new CaptChaException("验证码错误或已过期");
    }

    @Override
    public String token(String username, String password) {

        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(username, password);

        LoginUser loginUser = (LoginUser) authenticationManager.authenticate(authenticationToken).getPrincipal();

        return JwtUtils.createToken(loginUser);
    }


}
